/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.heyma.web.system;

import java.util.HashMap;
import java.util.Map;
import org.heyma.core.security.CustomUserDetails;
import org.heyma.core.service.IEntityServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author John
 */
@Controller
public class InitController {

    @Autowired
    IEntityServices service;

    @RequestMapping(value = "/main")
    public String main() {
        return "/system/ApplicationMainPage";
    }

    @RequestMapping(value = "/header")
    public String header(Model model) {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        CustomUserDetails user = (CustomUserDetails) auth.getPrincipal();

        Map<String, Object> u = new HashMap<String, Object>();
        u.put("id_usuario", user.getUsername());
        u.put("nombres", user.getNombre());
        u.put("paterno", user.getApellido());
        u.put("materno", "");
        u.put("tipo_usuario", user.getAuthorities().toArray()[0]);

        model.addAttribute("usuario", u);
        return "/header/HeaderView";
    }

    @RequestMapping(value = "/userfoto/{id}")
    public @ResponseBody String userFoto(@PathVariable String id) {
        String img = (String) service.getExistObject("sys", "usuario", "usuario", id).get("usuario_imagen");
        return "data:image/jpeg;base64," + img;        
    }
        
    @RequestMapping(value = "/index")
    public String index(Model model) {
        Map<String, Object> u = new HashMap<String, Object>();

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        CustomUserDetails user = (CustomUserDetails) auth.getPrincipal();

        u.put("categorias", user.getMenu());

        model.addAttribute("usuario", u);

        return "/index/IndexView";
    }

    @RequestMapping(value = "/portal")
    public String portal() {
        return "/portal/EnterPoint";
    }

    @RequestMapping(value = "/viewexplorer/{view}")
    public String viewExplorer(@PathVariable String view) {
        return "/" + view;
    }
}
